#!/bin/bash
set -e;

# DSM Config
username="$1"
password="$2"
hostname="$3"
ipAddr="$4"

API_TOKEN="$password"
# 你的域名
ZONE_NAME="$username"
# 子域名
DNS_NAME="$hostname"


# 获取IPV6地址
netinfo=`ip -6 address|grep global|grep "/64"`
netinfo=${netinfo#*inet6 }
NEW_IP=`echo $netinfo|cut -d '/' -f1`

#echo "$(date '+%Y-%m-%d %H:%M:%S') New IP: $NEW_IP " >>ddns.log



# 获取 Zone ID
ZONE_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=${ZONE_NAME}" \
     -H "Authorization: Bearer ${API_TOKEN}" \
     -H "Content-Type: application/json" | jq -r '.result[0].id')

if [ -z "$ZONE_ID" ] || [ "$ZONE_ID" == "null" ]; then
    echo "无法获取 Zone ID，请检查域名和 API Token。"
    exit 1
fi

# 获取 DNS 记录 ID
DNS_RECORD=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records?name=${DNS_NAME}" \
     -H "Authorization: Bearer ${API_TOKEN}" \
     -H "Content-Type: application/json" )

DNS_RECORD_ID=$(echo "$DNS_RECORD" | jq -r '.result[] | select(.type == "AAAA").id')
DNS_RECORD_PROXIED=$(echo "$DNS_RECORD" | jq -r '.result[] | select(.type == "AAAA").proxied')


if [ -z "$DNS_RECORD_ID" ] || [ "$DNS_RECORD_ID" == "null" ]; then
    # 新增记录
    API_URL="https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records"
    # 更新 DNS 记录
    RESPONSE=$(curl -s -X POST "$API_URL" \
     -H "Authorization: Bearer ${API_TOKEN}" \
     -H "Content-Type: application/json" \
     --data "{
         \"type\": \"AAAA\",
         \"name\": \"${DNS_NAME}\",
         \"content\": \"${NEW_IP}\",
         \"ttl\": 120,
         \"proxied\": false
     }")
else
    # 更新记录
    API_URL="https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${DNS_RECORD_ID}"
    # 更新 DNS 记录
    RESPONSE=$(curl -s -X PUT "$API_URL" \
     -H "Authorization: Bearer ${API_TOKEN}" \
     -H "Content-Type: application/json" \
     --data "{
         \"type\": \"AAAA\",
         \"name\": \"${DNS_NAME}\",
         \"content\": \"${NEW_IP}\",
         \"ttl\": 120,
         \"proxied\": ${DNS_RECORD_PROXIED}
     }")
fi

# 检查更新结果
if echo "$RESPONSE" | grep -q '"success":true'; then
#    echo "DNS 记录更新成功！外网 IP 设置为：$NEW_IP"
#    echo "$NEW_IP update good" >> ddns.log
    echo "good";
else
#    echo "更新失败："
#    echo "$NEW_IP update badauth" >> ddns.log
    echo "badauth";
fi
